import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/media_detail_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/poster_detail_page.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail/bean/terminal_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail_modify_order/terminal_detail_modify_order_view_model.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail_modify_order/widgets/terminal_detail_modify_order_list_item_widget.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'dart:math' as Math;

/// 终端详情修改调整资源顺序页
///
/// @author: zengxiangxi
/// @createTime: 3/6/21 1:46 PM
/// @specialDemand:
class TerminalDetailModifyOrderPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "TerminalDetailModifyOrderPage";

  final String hsn;
  final String branchname;

  const TerminalDetailModifyOrderPage({Key key, this.hsn, this.branchname}) : super(key: key);

  @override
  _TerminalDetailModifyOrderPageState createState() =>
      _TerminalDetailModifyOrderPageState();

  ///跳转方法
  static Future<bool> navigatorPush(BuildContext context, String hsn, String branchname) {
    return RouterUtils.routeForFutureResult<bool>(
      context,
      TerminalDetailModifyOrderPage(
        hsn: hsn,
        branchname: branchname,
      ),
      routeName: TerminalDetailModifyOrderPage.ROUTER,
    );
  }
}

class _TerminalDetailModifyOrderPageState
    extends BaseState<TerminalDetailModifyOrderPage> {

  ValueNotifier<bool> _isAllowSaveValueNotifier;

  CommonListPageWidgetState<TerminalDetailListItemBean,
      TerminalDetailResponseBean> mState;

  TerminalDetailModifyOrderViewModel _viewModel;
  //用户自传列表
  List<TerminalDetailListItemBean> mUserList;
  //推送列表
  List<TerminalDetailListItemBean> mPushList;

  @override
  void initState() {
    super.initState();
    mUserList = new List();
    mPushList = new List();
    _viewModel = TerminalDetailModifyOrderViewModel(this);
    _isAllowSaveValueNotifier = ValueNotifier(false);
  }

  @override
  void dispose() {
    _isAllowSaveValueNotifier?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: _toMainColumnWidget(),
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: <Widget>[
        _toTopBarWidget(),
        Expanded(
          child: Stack(
            children: <Widget>[
              _toListWidget(),
              Positioned(
                bottom: 50 + ScreenUtils.getBottomBarH(context),
                left: (ScreenUtils.screenW(context) - 136)/2,
                child: CommonFixedHeightConfirmButtonWidget(
                  isAlive: true,
                  width: 136,
                  height: 40,
                  unSelectBgColor: Color(0xFF3A3F50),
                  selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                  unSelectTextStyle: TextStyle(
                    color: VgColors.INPUT_BG_COLOR,
                    fontSize: 15,
                  ),
                  selectedTextStyle: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    // fontWeight: FontWeight.w600
                  ),
                  text: "随机排序",
                  textLeftSelectedWidget: Padding(
                    padding: const EdgeInsets.only(right: 5),
                    child: Image(
                      image: AssetImage("images/icon_random.png"),
                      width: 18,
                      height: 14,
                    ),
                  ),
                  onTap: (){
                    _randomImages();
                  },
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "排序设置",
      isShowBack: true,
      rightWidget: ValueListenableBuilder(
        valueListenable: _isAllowSaveValueNotifier,
        builder: (BuildContext context, bool isAllowSave, Widget child) {
          return GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: (){
              if(!isAllowSave){
                VgToastUtils.toast(context, "请调整要修改的顺序");
                return;
              }
              List<TerminalDetailListItemBean> list = mState?.data;

              list?.removeWhere((element) => element.id == null || element.id.isEmpty);
              if(list == null || list.isEmpty){
                return;
              }
              String splitStr = list.map((e) => e.id).toList().join(",");
              _viewModel.saveTerminalOrder(context, splitStr,widget.hsn);
            },
            child: CommonFixedHeightConfirmButtonWidget(
              isAlive: isAllowSave,
              width: 48,
              height: 24,
              unSelectBgColor: Color(0xff3a3f50),
              selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
              unSelectTextStyle: TextStyle(
                  color: VgColors.INPUT_BG_COLOR,
                  fontSize: 12,
                  fontWeight: FontWeight.w600
              ),
              selectedTextStyle: TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                  fontWeight: FontWeight.w600
              ),
              text: "保存",
            ),
          );
        },
      ),
    );
  }

  Widget _toListWidget() {
    return CommonListPageWidget<TerminalDetailListItemBean,
        TerminalDetailResponseBean>(
      enablePullUp: false,
      enablePullDown: false,
      queryMapFunc:(int page) => {
        "authId": UserRepository.getInstance().authId ?? "",
        "hsn": widget?.hsn ?? "",
      },
      parseDataFunc: (VgHttpResponse resp) {
        return TerminalDetailResponseBean.fromMap(resp?.data, isCache: true);
      },
      stateFunc: (CommonListPageWidgetState<TerminalDetailListItemBean,
          TerminalDetailResponseBean> state){
        mState = state;
      },
      itemBuilder: (BuildContext context, int index, itemBean) {
        return TerminalDetailModifyOrderListItemWidget(
          index: index,
          itemBean: itemBean,
          onTap: _onTap,
          onAccept: (int start,int end){
            _processState(start,end);
          },);
      },
      netUrl:NetApi.TERMINAL_PLAY_LIST_API,
      httpType: VgHttpType.get,
    );
  }

  _onTap(TerminalDetailListItemBean itemBean) {
    if(itemBean.isHtml()){
      PosterDetailPage.navigatorPush(context, itemBean.htmlurl, itemBean.id,
          itemBean.likeflg, itemBean.cretype,
          widget?.hsn, false, itemBean.logoflg, itemBean.addressflg, itemBean.diyflg, "01",
          itemBean.addressdiy, itemBean.namediy, itemBean.logodiy,
          itemBean.splpicurl, itemBean.pictype);
    }else{
      MediaDetailPage.navigatorPush(context, itemBean?.picid, "01", id: itemBean?.id);
    }
  }

  void _processState(int start,int end){
    print("拖拽调整： $start - $end");
    List list = mState?.data;
    if(list == null || list.isEmpty){
      return;
    }
    var removeItem = list.removeAt(start);
    list.insert(end, removeItem);
    mState?.setState(() { });
    _isAllowSaveValueNotifier?.value = true;
  }

  void _randomImages(){
    mUserList.clear();
    mPushList.clear();
    mState?.data?.forEach((element) {
      if("00" == element?.uploadflg??""){
        //自传
        mUserList.add(element);
      }else{
        //推送
        mPushList.add(element);
      }
    });
    mPushList.shuffle();
    mUserList.shuffle();
    mState?.data?.clear();
    mState?.data?.addAll(mPushList);
    mState?.data?.addAll(mUserList);
    // mState?.data?.shuffle();
    mState?.setState(() { });
    _isAllowSaveValueNotifier?.value = true;
  }
}
